package com.example.note2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;

public class EditActivity extends AppCompatActivity {

    private long mId;
    private String mText;
    private EditText tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        Intent intent = getIntent();
        mId = intent.getLongExtra("id", 0);
        if (mId == 0) {
            getSupportActionBar().setTitle("新建");
        } else {
            getSupportActionBar().setTitle("修改");
        }
        mText = intent.getStringExtra("text");
        tvContent = findViewById(R.id.text_view);
        tvContent.setText(mText);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        String t = tvContent.getText().toString();
        if (!TextUtils.isEmpty(t)) {
            if (mId == 0) {
                Note note = new Note();
                note.setText(tvContent.getText().toString());
                note.setTime(System.currentTimeMillis());
                note.save();
            } else if (t != mText) {
                Note note = new Note();
                note.setText(tvContent.getText().toString());
                note.setTime(System.currentTimeMillis());
                note.update(mId);
            }
        }
    }
}
